/**
 * Copyright (c) 2012, Hakans Pirates - 
 * Johan Andersson spaiki17@gmail.com, 
 * Mattias Lundberg lundberg.mattias@gmail.com, 
 * Samuel Sjodin sjoodin@gmail.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <organization> nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *  
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package pirates.network;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import pirates.Settings;
import pirates.notifications.Notify;

/**
 * 
 * @author mattias
 */
public class AuthRegistror {

	private static String ADD_COMMAND = "/addserver/";
	private static String DEL_COMMAND = "/delserver/";
	private static String RENEW_COMMAND = "/renew/";
	private String servername = "";

	public boolean register(String servername) {
		this.servername = servername;
		boolean authed = false;
		for (String server : Settings.AUTHSERVERS) {
			if (auth(server, servername, ADD_COMMAND)) {
				Runtime.getRuntime().addShutdownHook(new ShutdownHook(server));
				Thread renew = new Renewer(server);
				renew.start();
				authed = true;
			}
		}
		return authed;
	}

	public boolean auth(String server, String servername, String command) {

		URL url = null;
		try {
			url = new URL("http://" + server + command);
		} catch (MalformedURLException ex) {
			return false;
		}
		HttpURLConnection urlConn = null;
		try {
			urlConn = (HttpURLConnection) url.openConnection();
		} catch (IOException ex) {
			return false;
		}

		urlConn.setDoInput(true);

		urlConn.setDoOutput(true);

		urlConn.setUseCaches(false);

		try {
			urlConn.setRequestMethod("POST");
		} catch (ProtocolException ex) {
			return false;
		}

		try {
			urlConn.connect();
		} catch (IOException ex) {
			return false;
		}

		DataOutputStream output = null;
		DataInputStream input = null;

		try {
			output = new DataOutputStream(urlConn.getOutputStream());
		} catch (IOException ex) {
			return false;
		}

		String content;
		try {
			content = "servername=" + URLEncoder.encode(servername, "UTF8");
		} catch (UnsupportedEncodingException ex) {
			return false;
		}

		try {
			output.writeBytes(content);
			output.flush();
			output.close();
		} catch (IOException ex) {
			return false;
		}

		String str = null;
		try {
			InputStream a = urlConn.getInputStream();
			input = new DataInputStream(a);

			while (null != ((str = input.readLine()))) {
				if (str.equals("OK")) {
					return true;
				}
			}
			input.close();
		} catch (IOException ex) {
			return false;
		}

		return false;
	}

	public void run() {
	}

	private class ShutdownHook extends Thread {

		private String server;

		public ShutdownHook(String server) {
			this.server = server;
		}

		@Override
		public void run() {
			auth(server, servername, DEL_COMMAND);
			Notify.stdout("Sucessfully shut down server.");
		}
	}

	private class Renewer extends Thread {

		private String server;

		public Renewer(String server) {
			this.server = server;
		}

		@Override
		public void run() {
			while (true) {
				if (auth(server, servername, RENEW_COMMAND)) {
					Notify.debug("Reauthed");
				} else {
					Notify.debug("Failed to reauth");
				}
				try {
					Thread.sleep(Settings.REAUTH_RATE * 1000);
				} catch (Exception e) {
				}
			}
		}
	}
}
